package com.htj.filter;

import com.htj.setting.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 * 因为拦截器不会拦截web下的jsp,所以加入过滤器
 * 拦截器拦截规则 拦截以jsp结尾的
 * *.jsp
 * 过滤器
 * /**拦截全部
 *
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute("user");
        //如果是登录页直接放行
        if("/login.jsp".equals(request.getServletPath())){
            chain.doFilter(servletRequest,servletResponse);
        }else{
            if(user != null){
                chain.doFilter(servletRequest,servletResponse);
            }else{
                //sendRedirect的地址是(项目名称加jsp)
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
